package oog.product.control;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import oog.product.ReqUtil;
import oog.product.Util;
import oog.product.biz.ProductBiz;
import oog.product.entity.Product;
import oog.product.form.SearchForm;

/**
 * Servlet implementation class SearchServlet
 */
public class SearchServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    super.service(request, response);
	    LOG.debug("service.START");
	    SearchForm form = (SearchForm) ReqUtil.parseRequest(request, SearchForm.class);
	    
	    LOG.debug("cmd=" + form.getCmd());
	    
	    if ("search".equals(form.getCmd())) {
	        List<Product> productList = null;
	        LOG.debug("text=" + form.getText() + ";alphabetRange=" + form.getAlphabetRange());
	        if (Util.isNNandNB(form.getText())) { // search by text
	            productList = ProductBiz.searchByText(form.getText());
	        } else if (form.getAlphabetRange() != null) { // search by Alphabet
	            char fromChar = form.getAlphabetRange().toString().charAt(0);
	            char toChar = form.getAlphabetRange().toString().charAt(1);
	            productList = ProductBiz.searchByAlphabet(fromChar, toChar);
	        }
	        if (productList != null) {
	            request.setAttribute(KEY_PRODUCTLIST, productList);
	        }
	        request.getRequestDispatcher(PAGE_PRODUCT_SEARCH).forward(request, response);
	    } else if ("addProduct".equals(form.getCmd())) { // Goto screen Add Product
	        request.getRequestDispatcher(PAGE_PRODUCT_ADD).forward(request, response);
	    }
	}

}
